# -*- coding: utf-8 -*-

import sys
import os
import jinja2
import werkzeug.urls
import urllib
import simplejson

from openerp import http
from openerp.http import request
from openerp.osv import orm
from openerp.addons.dftg_weixin.application.application_test import WxAppCropTest

SUPERUSER_ID = 1

if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'html'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_weixin', "html")

env = jinja2.Environment('<%', '%>', '${', '}', '%', loader=loader, autoescape=True)


# 拦截所有HTTP请求，检查是否有微信回调验证参数
# 有验证参数的话则进行验证，验证后跳转到业务页面
class account_account_message(orm.AbstractModel):
    _inherit = 'account.account'

    # 统计消息
    def statistics_message(self, cr, uid, context=None):
        code_list = ['1', '2', '10', '1122', '1123', '1231', '2801', '2202', '2205', '2802']
        account_ids = self.search(cr, uid, [('code', 'in', code_list)], context=context)
        account_list = []
        for account in self.browse(cr, uid, account_ids, context=context):
            account_list.append({'name': account.name, 'code': account.code, 'balance': account.balance})

        self.send_to_weixin_user(cr, uid, simplejson.dumps(account_list), 1)
        return account_list

    def send_to_weixin_user(self, cr, uid, content, to_user_id, context =None):
        wx_api_sed_text = WxAppCropTest()
        contact_id = self.pool.get('weixin.contacts').search(cr, uid, [('odoo_user_id', '=', to_user_id)], context=context)
        if contact_id:
            wx_api_sed_text.wxapi.send_text(content, wx_api_sed_text.APP_ID, safe="0", touser=str(contact_id[0]))
        return True

